import pandas as pd
from snapshot_pyppeteer import snapshot
from pyecharts.charts import Radar
from pyecharts import options as opts
from pyecharts.render import make_snapshot
import json
import uuid
import numpy as np
from pyecharts.charts import Bar

def demo(excelPathJson):
    s1 = json.dumps(excelPathJson)
    dict1 = json.loads(s1)
    print(dict1)
    # 导入数据
    # thousands去除千分号,资产负债表
    data_all = pd.read_excel(dict1['dataAll'], thousands="，")
    data_L = pd.read_excel(dict1['dataL'], thousands="，")  # thousands去除千分号，利润表
    # thousands去除千分号，现金流量表
    data_X = pd.read_excel(dict1['dataX'], thousands="，")

    def anal(data, lis, z):
        balance = data.columns.values[0]  # 获取项目名称列列名
        data.index = data[balance]  # 修改列名,将项目名称作为行索引
        Z = data[balance].apply(str)  # 空值转为字符串
        a = data[Z.str.contains(lis)]
        # print("a.shape:", a.shape)
        if a.shape[0] == 0:
            vs = [0, 0]
        else:
            b = a.iloc[z]
            # print("b.shape:", b.shape)
            for j in range(len(b)):
                if type(b[j]) == str:
                    b[j] = str(b[j]).replace(".", "")
                    vs = []
                    if b[j].isdigit() is True and float(b[j]) - 50 > 0:
                        vs.append(float(b[j]))
                        print(j)
                        print(len(b))
                        if j + 1 <= len(b) - 1:
                            b[j + 1] = str(b[j + 1]).replace(".", "")
                            vs.append(float(b[j + 1]))
                        else:
                            vs.append(0)
                        break
                    else:
                        vs = [0, 1]
                else:
                    vs = [0, 2]
        return vs

    def po(x):
        if np.isinf(x) == True:
            x = 0
        elif np.isnan(x) == True:
            x = 0
        else:
            x = x
        return x
    # 获取数据
    tass = anal(data_all, '资产总|债和所', z=0)  # 资产总额
    equity = anal(data_all, '权益合|益\\(或股东权益\\)合', z=-1)  # 所有者权益
    cash_end = anal(data_X, '净额', z=0)  # 期末现金及现金等价物
    cur_lia = anal(data_all, "流动负债合", z=0)  # 流动负债
    nin = anal(data_L, '、净利润|净利润|润\\(净', z=0)  # 净利润
    turnover = anal(data_L, '总收|业总|入', z=0)  # 营业总收入
    basic_eps = anal(data_L, '本每', z=0)  # 基本每股收益
    # print(tass ,equity,cash_end, cur_lia, nin,turnover,basic_eps)
    # 财务指标计算，当年数据
    EM = po(np.around(np.array(tass[0]) / np.array(equity[0]), 2))  # 权益乘数
    EPS = po(np.around(np.array(basic_eps[0]) / 100, 2))  # 基本每股收益
    XJBL = po(np.around(np.array(cash_end[0]) / np.array(cur_lia[0]), 2))  # 现金比率
    EAS = po(np.around(np.array(turnover[0]) / np.array(tass[0]), 2))  # 资产周转率
    NPS = po(np.around(np.array(nin[0]) / np.array(turnover[0]), 2))  # 销售净利润率

    # 财务指标计算，上年数据
    EM1 = po(np.around(np.array(tass[1]) / np.array(equity[0]), 2))  # 权益乘数
    EPS1 = po(np.around(np.array(basic_eps[1]) / 100, 2))  # 基本每股收益
    XJBL1 = po(np.around(np.array(cash_end[1]) / np.array(cur_lia[1]), 2))  # 现金比率
    EAS1 = po(np.around(np.array(turnover[1]) / np.array(tass[1]), 2))  # 资产周转率
    NPS1 = po(np.around(np.array(nin[1]) / np.array(turnover[1]), 2))  # 销售净利润率
    # 行业水平
    avg_EM = 2.09
    avg_EAS = 0.65
    avg_XJBL = 0.30
    avg_NPS = 0.06
    avg_EPS = 0.38
#  小程序输出数据 com_data为公司数据，avg_data为同行数据
#   title_data = {"股权收益", "盈利能力", "偿债能力", "运营效率", "资本结构"}
    com_data = {"基本每股收益：": EPS, "销售净利润率": NPS,
                "现金流量比率": XJBL, "总资产周转率": EAS, "权益乘数": EM}
    com_data = {"基本每股收益：": EPS1, "销售净利润率": NPS1,
                "现金流量比率": XJBL1, "总资产周转率": EAS1, "权益乘数": EM1}
    avg_data = {"基本每股收益：": avg_EPS, "销售净利润率": avg_NPS,
                "现金流量比率": avg_XJBL, "总资产周转率": avg_EAS, "权益乘数": avg_EM}
    # print(com_data)
    # print(avg_data)
# 财务指标评价  （小程序中显示文字）
    # 基本每股收益
    if EPS == 0:
        None
        basicEarningsPerShare = ""
    elif EPS <= 0.304:
        basicEarningsPerShare = "本企业股东收益水平较低；"
    elif 0.304 < EPS <= 0.456:
        basicEarningsPerShare = "本企业股东收益水平处于行业平均水平；"
    else:
        basicEarningsPerShare = "本企业股东收益水平较高；"
    #  销售利润率
    if NPS == 0:
        None
        salesProfitMargin = ""
    elif NPS <= 0.048:
        salesProfitMargin = "销售净利率较低，建议尝试提高管理效率或提升产品差异化水平，提高盈利水平；"
    elif 0.048 < NPS <= 0.072:
        salesProfitMargin = "销售净利率一般，建议尝试改变销售策略，提高销售收入，同时降低运营成本；"
    else:
        salesProfitMargin = "销售净利率较高，企业盈利能力较强，建议维持市场份额和产品创新能力；"
    # 现金流量负债比率
    if XJBL == 0:
        None
        cashFlowLiabilityRatio = ""
    elif XJBL <= 0.24:
        cashFlowLiabilityRatio = "偿还短期债务的能力较弱，如不采取措施，企业可能没有足够的现金偿还债务；"
    elif 0.24 < XJBL <= 0.36:
        cashFlowLiabilityRatio = "偿还短期债务的能力一般，企业现金流刚好能够抵偿债务；"
    else:
        cashFlowLiabilityRatio = "偿还短期债务的能力较强，企业现金流比较充裕；"

    #  总资产周转率
    if EAS == 0:
        None
        turnoverOfTotalAssets = ""
    elif EAS <= 0.52:
        turnoverOfTotalAssets = "资产使用效率较低，企业运营效率和销售能力有待改善，可以尝试调整销售策略；"
    elif 0.52 < EAS <= 0.78:
        turnoverOfTotalAssets = "资产使用效率中等，企业销售能力和运营效率一般，可以尝试提高资产利用率，使企业资产得到充分利用；"
    else:
        turnoverOfTotalAssets = "资产使用效率较高，企业销售能力较强，资产投资的效益较好；"
    # 权益乘数
    if EM == 0:
        None
        financialIndexEvaluation = ""
    elif EM <= 1.672:
        financialIndexEvaluation = "所有者权益占资本的比重较小，债权比重较高，虽然财务杠杆效应较强，但企业整体债务风险较大。"
    elif 1.672 < EM <= 2.508:
        financialIndexEvaluation = "债权在总资本中的比重中等，企业债务风险中等。"
    else:
        financialIndexEvaluation = "所有者权益占资产的比重较大，企业整体债务风险较小，但也没有很好利用财务杠杆。"

# 分析可视化  生成雷达图
    AA = np.around(EM / avg_EM, 2)
    BB = np.around(EPS / avg_EPS, 2)
    CC = np.around(XJBL / avg_XJBL, 2)
    DD = np.around(NPS / avg_NPS, 2)
    EE = np.around(EAS / avg_EAS, 2)
    v1 = [AA, BB, CC, DD, EE]  # 行业水平
    #data = [{"value": [AA, BB, CC, DD, EE], "name": ""}]  # 公司数据
    data = [{"value": [BB, DD, CC, EE, AA], "name": ""}]  # 公司数据
    data1 = [{"value": [1, 1, 1, 1, 1], "name": ""}]  # 行业水平
    c_schema = [
        {"name": "基本每股收益", "max": max(v1), "min": 0},
        {"name": "销售净利润率", "max": max(v1), "min": 0},
        {"name": "现金流量比率", "max": max(v1), "min": 0},
        {"name": "总资产周转率", "max": max(v1), "min": 0},
        {"name": "权益乘数", "max": max(v1), "min": 0},
    ]
    uid3 = str(uuid.uuid1())
    c = (
        Radar(init_opts=opts.InitOpts(width="540px", height="400px", bg_color="#CCCCCD"))
            # .set_colors(["black"])
            .add_schema(
            schema=c_schema,
            shape="circle",
            center=["50%", "50%"],
            radius="75%",
            angleaxis_opts=opts.AngleAxisOpts(
                min_=0,
                max_=360,
                is_clockwise=False,
                # interval=4,
                axistick_opts=opts.AxisTickOpts(is_show=False),
                axislabel_opts=opts.LabelOpts(is_show=False),
                axisline_opts=opts.AxisLineOpts(is_show=False),
                splitline_opts=opts.SplitLineOpts(is_show=False),
            ),
            textstyle_opts=opts.TextStyleOpts(color="Black"),
            radiusaxis_opts=opts.RadiusAxisOpts(
                min_=0,
                max_=max(v1),
                interval=max(v1) / 0.5,
                splitarea_opts=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
                ),
                axislabel_opts=opts.AxisLineOpts(is_show=False),
            ),
            polar_opts=opts.PolarOpts(),
            splitarea_opt=opts.SplitAreaOpts(is_show=True),
            splitline_opt=opts.SplitLineOpts(is_show=True),
        )
            .add(
            series_name="公司本年数据",
            data=data,
            areastyle_opts=opts.AreaStyleOpts(opacity=0.1),
            # linestyle_opts=opts.LineStyleOpts(width=1),
            linestyle_opts=opts.LineStyleOpts(color="#CD0001"),
            label_opts=opts.LabelOpts(color="#CD0001")
        )
            .add(
            series_name="行业水平",
            data=data1,
            # areastyle_opts=opts.AreaStyleOpts(opacity=0.1),
            # linestyle_opts=opts.LineStyleOpts(width=1),
            linestyle_opts=opts.LineStyleOpts(color="Black"),
            label_opts=opts.LabelOpts(color="Black")
        )
        #.render(r"Radar_angle_radius_axis" + uid3 + ".html")
    )
    uid = str(uuid.uuid1())
    pngPath = str("png/Radar"+uid+".png")
    make_snapshot(snapshot, c.render(r"html/Radar_angle_radius_axis" + uid3 + ".html"), pngPath)
    # 》》》》》》》》》》》》》》》》》》》》》
    # 柱状图
    val1 = [EM, EAS, XJBL, NPS, EPS]  # 本年数据
    val2 = [EM1, EAS1, XJBL1, NPS1, EPS1]  # 上年数据
    xax = ["权益乘数", "总资产周转率", "现金流量比率", "销售净利润率", "基本每股收益"]
    # R ={"权益乘数": [EM, EM1], "总资产周转率": [EAS, EAS1], "现金流量比率": [XJBL, XJBL1], "销售净利润率": [NPS, NPS1], "基本每股收益":[EPS, EPS1]}
    uid4 = str(uuid.uuid1())
    c1 = (
        Bar(init_opts=opts.InitOpts(bg_color="#CCCCCD"))
            .add_xaxis(xax)
            .add_yaxis("本年数据", val1)
            .add_yaxis("上年数据", val2)
            .reversal_axis()
            .set_series_opts(label_opts=opts.LabelOpts(position="right"))
            .set_global_opts(title_opts=opts.TitleOpts(title=""))
         #.render(r"Bar_reversal_axis" + uid4 + ".html")
    )
    uid = str(uuid.uuid1())
    pngPath1 = str("png/Bar"+uid+".png")
    make_snapshot(snapshot, c1.render(r"html/Bar_reversal_axis" + uid4 + ".html"), pngPath1)
    # 》》》》》》》》》》》》》》》》》》》》
    titleData = {
        'EPS': '股权收益',
        'NPS': '盈利能力',
        'XJBL': '偿债能力',
        'EAS': '运营效率',
        'EM': '资本结构'
    }
    # 本年数据
    financialData = {
        'EPS': EPS,
        'NPS': NPS,
        'XJBL': XJBL,
        'EAS': EAS,
        'EM': EM
    }

    # 上年数据
    financialData1 = {
        'EPS': EPS1,
        'NPS': NPS1,
        'XJBL': XJBL1,
        'EAS': EAS1,
        'EM': EM1
    }
    industryLevel = {
        'EPS': avg_EPS,
        'NPS': avg_NPS,
        'XJBL': avg_XJBL,
        'EAS': avg_EAS,
        'EM': avg_EM
    }
    description = {
        'financialIndexEvaluation': financialIndexEvaluation,
        'basicEarningsPerShare': basicEarningsPerShare,
        'cashFlowLiabilityRatio': cashFlowLiabilityRatio,
        'salesProfitMargin': salesProfitMargin,
        'turnoverOfTotalAssets': turnoverOfTotalAssets
    }

    conclusion = {'titleData':titleData, 'pngPath': pngPath, 'pngPath1': pngPath1, 'financialData': financialData,
                  "financialData1": financialData1,
                  'industryLevel': industryLevel, 'description': description}

    return conclusion
    # return {"pngPath": pngPath, "financialData": financialData, "industryLevel": industryLevel, "description": description}


"""
Gallery 使用 pyecharts 1.1.0
参考地址: https://echarts.baidu.com/examples/editor.html?c=radar

目前无法实现的功能:

1、雷达图周围的图例的 textStyle 暂时无法设置背景颜色
"""


if __name__ == '__main__':
    excelPathJson = {}
    excelPathJson['dataAll'] = 'C:/Users/Administrator/Desktop/资产负债表.xls'
    excelPathJson['dataL'] = 'C:/Users/Administrator/Desktop/利润表.xls'
    excelPathJson['dataX'] = 'C:/Users/Administrator/Desktop/现金流量表.xls'
    pngPath = demo(excelPathJson)

